import * as feishuService from '@/api/service/FeishuService'
import Md5 from 'crypto-js/Md5'
import * as CryptoJS from 'crypto-js'

const SALT = 'qD1!kD'

const aesSecretKey = CryptoJS.enc.Utf8.parse("b1ebde633a7eddacef881173a87b3856");
const aesIv = CryptoJS.enc.Utf8.parse("rU2jS4iK0kA1hD1b");


/**
 * key 加密
 * @param key
 * @returns
 */
function encodeKey(key: string):string{
  return Md5(key + '{' + SALT + '}').toString()
}

/**
 * 加密
 * @param data
 * @returns
 */
function encodeValue(data: string): string{
  const encrypted = CryptoJS.AES.encrypt(data, aesSecretKey, {
      iv: aesIv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.toString()
}

/**
 * 解密
 * @param value
 * @returns
 */
function decodeValue(encryptedData: string): string{
  const decrypted = CryptoJS.AES.decrypt(encryptedData, aesSecretKey, {
      iv: aesIv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
  });
  return decrypted.toString(CryptoJS.enc.Utf8);
}

/**
 * 表格列表
 */
export function findList(queryBody?:any): Promise<any> {
  const tableId = globalThis.tableConfig.system
  return feishuService.appTableRecords(tableId, queryBody, 100)
}

/**
 * 通过键名获取
 * @param key
 * @returns
 */
export async function findByKey(key: string): Promise<any> {
  key = encodeKey(key);
  console.log(key)
  const queryBody:any = {
    filter: {
      conjunction:'and',
      conditions: [
        {
          field_name:'键',
          operator:'is',
          value:[key],
        }
      ]
    }
  }
  const tableId = globalThis.tableConfig.system
  const response = await feishuService.appTableRecordList(tableId, queryBody);
  const items = response.data.items;
  let data = items.length > 0 ? items[0] : null;

  if(data){
    data = globalThis.parseFeishuRecord(data)
    data['值'] = decodeValue(data['值'])
  }
  return data
}

/**
 * 保存
 * @param record
 * @returns
 */
export async function save(record: any):Promise<any>{
  const tableId = globalThis.tableConfig.system

  const oldRecord = await findByKey(record['键']);
  const fields = {
    "键": encodeKey(record['键']),
    "值": encodeValue(record['值'])
  }
  if(oldRecord){
    return feishuService.updateRecord(tableId, oldRecord.recordId, fields)
  }
  else{
    return feishuService.addRecord(tableId, fields)
  }
}


/**
 * 新增记录
 * @param record
 */
export function addRecord(record:any):Promise<any>{
  const tableId = globalThis.tableConfig.system
  const fields = {
    "键": encodeKey(record['键']),
    "值": encodeValue(record['值'])
  }
  return feishuService.addRecord(tableId, fields)
}

/**
 * 更新记录
 * @param record
 */
export function updateRecord(recordId: string, record: any):Promise<any>{
  const tableId = globalThis.tableConfig.system
  const fields = {
    "键": encodeKey(record['键']),
    "值": encodeValue(record['值'])
  }

  return feishuService.updateRecord(tableId, recordId, fields)
}


/**
 * 删除记录
 * @param recordId
 */
export function removeRecord(recordId:string):Promise<any>{
  const tableId = globalThis.tableConfig.system
  return feishuService.removeRecord(tableId, recordId);
}
